<template>
  <div class="mt-1">
    <van-form>
      <h4 style="margin: 0 0 0.2rem 1rem; color: gray">
        当前产区:{{ this.$store.getters.productionLine }}
      </h4>
      <van-field
        v-model="code"
        clearable
        ref="pmfocus"
        @focus="stopKeyborad"
        label="拍码"
        placeholder="请输入拍码"
      />
      <van-field
        :value="palletNumber"
        readonly
        label="拍号"
        placeholder="拍号"
      />
      <van-row>
        <van-col span="17"
          ><van-field
            v-model="rollid"
            clearable
            label="膜卷号"
            placeholder="请输入膜卷号"
            ref="mjfocus"
            @focus="stopMJborad"
        /></van-col>
        <van-col span="6"
          ><van-button block type="info" class="mt-1" @click="addNumber"
            >添加</van-button
          ></van-col
        >
      </van-row>
      <ag-grid-vue
        style="width: 100%; height: 52vh"
        class="ag-theme-alpine mt-1"
        :columnDefs="columnDefs"
        :defaultColDef="defaultColDef"
        :gridOptions="gridOptions"
        :singleClickEdit="true"
        rowSelection="multiple"
        :rowData="rowData"
      >
      </ag-grid-vue>
      <van-dialog
        v-model="Rollvisible"
        show-cancel-button
        :beforeClose="handleSure"
        confirm-button-color="rgba(25, 137, 250,1)"
      >
        <div class="roll-content">
          <van-radio-group v-model="radio" direction="horizontal">
            <van-radio name="0" icon-size="26px">未完成</van-radio>
            <van-radio name="1" icon-size="26px">已完成</van-radio>
          </van-radio-group>
          <van-cell
            class="cellDate"
            title="结束日期"
            :value="endAt"
            @click="endAtVisible = true"
          />
          <van-popup v-model="endAtVisible" position="bottom">
            <van-grid direction="horizontal" :column-num="5">
              <van-grid-item text="年" />
              <van-grid-item text="月" />
              <van-grid-item text="日" />
              <van-grid-item text="时" />
              <van-grid-item text="分" />
            </van-grid>
            <van-datetime-picker
              type="datetime"
              title="选择日期时间"
              v-model="endAtDate"
              @confirm="onConfirm"
              @cancel="endAtVisible = false"
            />
          </van-popup>
          <!--          <van-calendar
            v-model="endAtVisible"
            @confirm="onConfirm"
            :min-date="minDate"
          /> -->
        </div>
      </van-dialog>
      <van-row type="flex" gutter="10" justify="center">
        <van-col span="7">
          <van-button type="warning" class="mt-1" block @click="ChangeData"
            >修改</van-button
          ></van-col
        >
        <van-col span="7">
          <van-button block type="danger" class="mt-1" @click="BackNumber"
            >撤回</van-button
          ></van-col
        >
        <van-col span="7">
          <van-button type="info" class="mt-1" block @click="SubmitData"
            >提交</van-button
          ></van-col
        >
      </van-row>
      <audio src="../../assets/warning.mp3" preload="auto" id="bgMusic"></audio>
    </van-form>
  </div>
</template>

<script>
import dayjs from "dayjs";
import { Grid, GridItem } from "vant";
import { AgGridVue } from "ag-grid-vue";
import { CODE_LENGTH } from "../../config";
import { Dialog } from "vant";
import { AgGrid } from "../../mixins/AgGrid";
import { parseQRCode, toast, dateToString } from "../../utils/common";
import { GetWindNumber, SaveWindNumber } from "../../api/feeding";

export default {
  name: "WIP",
  components: {
    AgGridVue,
    [Dialog.Component.name]: Dialog.Component,
    [Grid.name]: Grid,
    [GridItem.name]: GridItem,
  },
  mixins: [AgGrid],
  data() {
    let endAt = dayjs();
    return {
      code: "",
      rollid: "",
      material: "",
      palletNO: "",
      radio: "",
      palletNumber: "",
      Rollvisible: false,
      endAtDate: endAt.toDate(),
      endAtVisible: false,
      minDate: new Date(2015, 0, 1),
      columnDefs: [
        { headerName: "膜卷号", field: "WindingNumber", width: 110 },
        { headerName: "物料号", field: "ProductId", width: 100 },
        { headerName: "拍号", field: "UniqueId", width: 100 },
        { headerName: "状态", field: "RollStatus", width: 70 },
        { headerName: "结束时间", field: "FinishedOn", width: 100 },
      ],
      rowData: [],
    };
  },
  computed: {
    endAt() {
      return dateToString(this.endAtDate);
    },
  },
  watch: {
    code(val) {
      if (val.length > CODE_LENGTH) {
        let res = parseQRCode(val);
        if (res) {
          this.material = res.materialCode;
          this.palletNO = res.palletNo;
          this.palletNumber = res.palletNo;
          this.GetWindNumber(res.palletNo);
          this.$refs.mjfocus.focus();
        } else {
          this.playMusic();
          toast("无法识别");
        }
      }
      this.code = "";
    },
    /*     endAt() {
      return dateToString(this.endAtDate);
    }, */
  },
  methods: {
    // 消除获取焦点时自动弹出键盘
    stopKeyborad() {
      this.$refs.pmfocus.$refs.input.setAttribute("readonly", "readonly");
      setTimeout(() => {
        this.$refs.pmfocus.$refs.input.removeAttribute("readonly");
      }, 200);
    },
    stopMJborad() {
      this.$refs.mjfocus.$refs.input.setAttribute("readonly", "readonly");
      setTimeout(() => {
        this.$refs.mjfocus.$refs.input.removeAttribute("readonly");
      }, 200);
    },
    //播放警示音
    playMusic() {
      setTimeout(() => {
        let audio = document.getElementById("bgMusic");
        audio.play();
      }, 200);
    },
    //获取卷心号
    async GetWindNumber(palletNO) {
      this.rowData = [];
      this.rollid = "";
      let res = await GetWindNumber(
        this.$store.getters.productionLine,
        palletNO,
        ""
      );
      //this.$store.getters.user
      if (res.Status == 200 && res.Data.length > 0) {
        let _this = this;
        res.Data.map((it) => {
          _this.rowData.push({
            WindingNumber: it.WindingNumber,
            CreatedOn: it.CreatedOn,
            ProductId: it.ProductId,
            UniqueId: it.UniqueId,
            Line: it.Line,
            Id: it.Id,
            RollStatus: 0,
          });
        });
        this.$refs.mjfocus.focus();
      } else if (res.Data.length == 0) {
        toast("此拍暂无数据,请直接添加");
      } else {
        toast(res.Msg);
      }
      console.log(res);
    },
    //添加膜卷
    addNumber() {
      if (this.rowData.find((it) => it.WindingNumber == this.rollid)) {
        toast("此膜卷号已存在，请勿重复添加");
      } else {
        this.rowData.push({
          WindingNumber: this.rollid,
          ProductId: this.material,
          UniqueId: this.palletNO,
          RollStatus: 0,
        });
      }
    },
    //撤回膜卷
    BackNumber() {
      let selectedData = this.gridApi.getSelectedRows();
      if (selectedData[0]) {
        //删除数组中的某个值
        let a = this.gridApi.updateRowData({ remove: selectedData });
        //删除rowData内此值
        this.rowData.splice(a.remove[0].childIndex, 1);
      } else {
        this.playMusic();
        toast("未选择需要撤销行");
      }
    },
    //提交膜卷
    async SubmitData() {
      let item = [];
      this.rowData.map((it) => {
        item.push({
          WindingNumber: it.WindingNumber,
          IsFinished: it.RollStatus,
          Id: it.Id,
          FinishedOn: it.FinishedOn,
        });
      });
      let res = await SaveWindNumber(
        this.$store.getters.productionLine,
        this.palletNO,
        this.$store.getters.user,
        item,
        this.material
      );
      if (res.Status == 200) {
        toast(res.Msg);
        this.rollid = "";
        this.rowData = [];
      } else {
        toast(res.Msg);
      }
      console.log(res);
      this.$refs.pmfocus.focus();
    },
    //修改状态
    ChangeData() {
      let selectedData = this.gridApi.getSelectedRows();
      if (selectedData[0]) {
        this.Rollvisible = true;
        this.getDefaultDate();
      } else {
        this.playMusic();
        toast("未选择需要撤销行");
      }
    },
    //弹窗按钮
    handleSure(action, done) {
      if (action === "confirm") {
        let selectedData = this.gridApi.getSelectedRows();
        selectedData[0].RollStatus = this.radio;
        selectedData[0].FinishedOn = this.endAt;
        this.gridApi.updateRowData({ updata: selectedData[0] });
        //this.gridApi.refreshCells();
        done();
      } else {
        done();
      }
    },
    //时间确认
    /*     formatDate(date) {
      return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
    }, */
    onConfirm() {
      //this.endAtDate = dateToString(this.endAtDate);
      //console.log(data);
      /* console.log(data);*/
      //this.endDate = data;
      this.endAtVisible = false;
      //this.endAtDate = this.formatDate(date);
    },
    //获取默认日期
    getDefaultDate() {
      this.endAtDate = dayjs().toDate();
      this.endAt = dateToString(this.endAtDate);
      /*      let nowDate = new Date();
      let year = nowDate.getFullYear();
      let month = nowDate.getMonth();
      let date = nowDate.getDate();
      let hour = nowDate.getHours();
      let minute = nowDate.getMinutes();
      let second = nowDate.getSeconds(); */
      //this.endAt = `${year}-${month}-${date} ${hour}:${minute}:${second}`;
    },
  },
  mounted() {
    this.$refs.pmfocus.focus();
    //this.getDefaultDate();
  },
};
</script>

<style >
.roll-content {
  width: 19rem;
  height: 30rem;
  margin: 1rem auto;
  line-height: 2rem;
  text-align: center;
}
.van-radio {
  margin-right: 1rem;
  margin-left: 2.6rem;
}
.cellDate {
  margin-top: 2rem;
  border: solid 1px rgb(201, 180, 221);
}
</style>